package com.stenio.fancat.pay;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stenio.fancat.common.FanCatException;
import com.stenio.fancat.common.HttpClient;
import com.stenio.fancat.domain.shop.FcEtOrder;
import com.stenio.fancat.domain.shop.FcGift;
import com.stenio.fancat.domain.user.UserRelationship;
import com.stenio.fancat.form.OrderForm;
import com.stenio.fancat.mapper.shop.FcGiftMapper;
import com.stenio.fancat.mapper.user.UserRelationshipMapper;
import com.stenio.fancat.mapper.wx.FcEtOrderMapper;
import com.stenio.fancat.mapper.wx.WxOrderMapper;
import com.stenio.fancat.util.DateUtil;
import com.stenio.fancat.util.StringUtil;
import com.stenio.fancat.util.XmlUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class Pay {
	private static final Logger logger = LoggerFactory.getLogger(Pay.class);
	public static final String SUCCESS = "SUCCESS";

	@Value("${pay.appid}")
	private String appid;
	@Value("${pay.mch-id}")
	private String mchId;
	@Value("${pay.key}")
	private String key;
	@Value("${pay.notice-url}")
	private String noticeUrl;
	@Value("${red.Addr}")
	private String ip;

	@Autowired
	private WxOrderMapper wxOrderMapper;

	@Autowired
	private FcEtOrderMapper fcEtOrderMapper;

	@Autowired
	private FcGiftMapper fcGiftMapper;

	@Autowired
	private UserRelationshipMapper userRelationshipMapper;

	public OrderResult placeOrder(OrderForm form) throws FanCatException {
		UserRelationship userRelationship = userRelationshipMapper.selectUserInfoById(form.getEtUserId());
		FcGift fcGift = fcGiftMapper.selectById(form.getId());
		Order order = new Order();
		//小程序id
		order.setAppid(appid);
		//商户号
		order.setMch_id(mchId);
		String random = RandomStringUtils.random(8, true, true);
		//随机字符串
		order.setNonce_str(random);
		//商品描述
		order.setBody(fcGift.getName());
		//标价金额单位分
		order.setTotal_fee(fcGift.getFee());
		//交易类型
		order.setTrade_type("JSAPI");
		//终端id  调用微信支付api的机器ip
		order.setSpbill_create_ip(ip);
		//商户订单号
		String currTime = DateUtil.getCurrTime();
		String strRandom = StringUtil.buildRandom(4)+"";
		String rechOrderNO = currTime + strRandom;
		order.setOut_trade_no(rechOrderNO);
		//通知地址
		order.setNotify_url(noticeUrl);
		//openId
		order.setOpenid(userRelationship.getOpenId());
		//签名
		order.setSign(new Md5Encryptor().encrypt(order, key));
		String xmlBody = XmlUtil.fromBean(order);
		HttpClient httpClient = new HttpClient();
		String result = httpClient.postXml("https://api.mch.weixin.qq.com/pay/unifiedorder", xmlBody);
		try {
			OrderResult orderResult = XmlUtil.toBean(result, OrderResult.class);
			logger.info("==>{}" , orderResult.toString());
			if (SUCCESS.equals(orderResult.getResult_code())) {
				//处理订单逻辑
				order.setStatus(0);
				wxOrderMapper.insert(order);
				FcEtOrder fcEtOrder = new FcEtOrder();
				fcEtOrder.setUserId(form.getUserId());
				fcEtOrder.setEtUserId(form.getEtUserId());
				fcEtOrder.setFee(fcGift.getFee());
				fcEtOrder.setReflectAmount(fcGift.getFee());
				fcEtOrder.setBabyId(form.getBabyId());
				fcEtOrder.setOutTradeNo(rechOrderNO);
				fcEtOrder.setStatus(0);
				fcEtOrder.setPage(form.getPage());
				fcEtOrder.setGiftId(form.getId());
				fcEtOrder.setCreateTime(new Date());
				fcEtOrder.setUpdateTime(new Date());
				fcEtOrderMapper.insert(fcEtOrder);
				String timeStamp = System.currentTimeMillis()+"";
				orderResult.setTimeStamp(timeStamp);
				String beforMD5 = "appId=" + appid + "&nonceStr=" + random + "&package=prepay_id=" + orderResult.getPrepay_id()
						+ "&signType=MD5" + "&timeStamp=" + timeStamp + "&key=" + key;
				String newSign = StringUtil.md5(beforMD5).toUpperCase();
				orderResult.setNonce_str(random);
				orderResult.setMiniSign(newSign);
				return orderResult;
			}
			throw new FanCatException(orderResult.getReturn_msg());
		} catch (IllegalAccessException | InstantiationException e) {
			throw new FanCatException("下单时出错");
		}
	}


	/**
	 * 微信回调通知订单结果，处理订单信息
	 * @param notice
	 * @return
	 * @throws FanCatException
	 */
	public Integer processNotice(Notice notice) throws FanCatException {
		String sign = new Md5Encryptor().encrypt(notice, key);
		if (!notice.getSign().equals(sign)) {
			throw new FanCatException("sign签名不正确");
		}
		Order order = new Order();
		if (SUCCESS.equals(notice.getReturn_code())) {
			order.setStatus(1);
		} else {
			order.setStatus(2);
		}
		return wxOrderMapper.update(order, new EntityWrapper<Order>().eq("total_fee", notice.getTotal_fee())
				.eq("status", 0).eq("out_trade_no", notice.getOut_trade_no()));
	}
}
